<?php

namespace app\common\model;

use app\common\model\goods\category\Region;
use app\common\model\goods\Giveaway;
use app\common\model\order\Goods;
use app\common\model\order\Order;
use app\common\model\user\Info;
use app\common\model\user\Level;
use app\common\model\user\Region as UserRegion;
use think\Db;
use think\Log;
use think\Model;

/**
 * 会员余额日志模型
 */
class MoneyLog extends Model
{

    // 表名
    protected $name = 'user_money_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    // 追加属性
    protected $append = [
        'money_text',
        'createtime_text',
    ];

    public function order()
    {
        return $this->belongsTo(Order::class, 'order_sn', 'sn', [], 'LEFT')->setEagerlyType(0);
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getTypeList()
    {
        return ['1' => __('收入'), '2' => __('支出')];
    }
    public function getMoneyTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['source_type']) ? $data['source_type'] : '');
        $list = $this->getMoneyType();
        return isset($list[$value]) ? $list[$value] : '';
    }
    const commission_change = [
        200,
        201,
        202,
        203,
        204,

        300,
        301,
        302,

        400,
        401,
        402,
        403,
        404,
    ];
    const money_change = [
        500,
        // => '余额支付',
        501,
        //=> '余额充值',
        502,
        //=> '余额退款',
    ];
    //返回变动字段
    public static function getChangeField($source_type)
    {

        $field = '';
        if (in_array($source_type, self::money_change)) {
            $field = 'money';
        }
        if (in_array($source_type, self::commission_change)) {
            $field = 'commission';
        }
        return $field;
    }
    public static function getMoneyType()
    {
        return [
            200 => '直推收益',
            201 => '平推收益',
            202 => '极差收益',
            203 => '服务收货区域收益',
            204 => '代理收货区域收益',

            300 => '佣金提现',
            301 => '佣金支付',
            302 => '提现失败',

            400 => '直推冻结佣金',
            401 => '平级冻结佣金',
            402 => '级差冻结佣金',
            403 => '服务收货区域冻结分佣',
            404 => '代理收货区域冻结分佣',

            500 => '余额支付',
            501 => '余额充值',
            502 => '余额退款',
        ];
    }
    /**
     * Notes:记录会员账户流水，如果变动类型是成长值，且是增加的，则调用更新会员等级方法。该方法应在添加用户账户后调用
     * @author: cjh 2020/12/15 11:49
     * @param int $user_id  用户id
     * @param float $amount 变动数量
     * @param int $change_type  变动类型：1-减少；2-增加
     * @param int $source_type 来源类型
     * @param string $source_id 来源id
     * @param string $source_sn 来源单号
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function income($user_id, $amount, $change_type, $source_type, $source_sn = '', $order_goods_id = 0, $uid = 0)
    {
        $user = new User;
        $user = $user->get($user_id);
        if (empty($user)) {
            return false;
        }
        $field = self::getChangeField($source_type);
        $before = $user->$field;
        if ($change_type == 1) {
            $user->setInc($field, $amount);
        } else {
            $user->setDec($field, $amount);
            $amount = -$amount;
        }
        $left_amount = $user->$field;
        $list = self::getMoneyType();
        $account_log = new self;
        $data['type'] = $change_type;
        $data['order_sn'] = $source_sn;
        $data['order_goods_id'] = $order_goods_id;
        $data['user_id'] = $user_id;
        $data['money'] = $amount ?? 0;
        $data['before'] = $before ?? 0;
        $data['after'] = $left_amount ?? 0;
        $data['memo'] = isset($list[$source_type]) ? $list[$source_type] : '';
        $data['source_type'] = $source_type;
        $data['class'] = $field;
        $data['uid'] = $uid;
        $account_log->allowField(true)->save($data);

        return true;
    }

    /**
     * @author LK
     * @date: 2023-10-23 
     * @param object $order  冻结佣金明细
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static function frozenlog_commission($order)
    {

        $goods = Goods::all(['order_id' => $order['id']]);

        foreach ($goods as $v) {
            //直推冻结金额
            $user = User::get($order->user_id);

            $giveaway_array = json_decode($v->giveaway_info, true);

            if ($giveaway_array == null || !$giveaway_array) {
                continue;
            }
            $range_ratio = $giveaway_array['partner_difference'];
            //服务收货区域冻结分佣
            $receiving = Info::get(['first_cate' => $v->first_cate, 'two_cate' => $v->two_cate, 'address' => $order->receiving_area, 'accredit' => 1]);
   

            if ($receiving) {
                $accredit_amount = 0;
                if (isset($giveaway_array['receiving_area']) && $giveaway_array['receiving_area'] > 0) {
                    $accredit_scale = $giveaway_array['receiving_area'];
                    if (isset($accredit_scale) && $accredit_scale > 0) {
                        $accredit = $accredit_scale / 100;
                        if ($accredit > 0) {
                            $accredit_amount = bcmul($v->pay_fee, $accredit, 2);
                        }

                        if ($accredit_amount > 0) {
                            FrozenLog::create([
                                'user_id' => $receiving->user_id,
                                'money' => $accredit_amount,
                                'order_id' => $order->id,
                                'order_goods_id' => $v->id,
                                'memo' => '服务收货区域冻结分佣',
                                'source_type' => 403,
                            ]);
                        }
                    }
                }
            }
            //代理收货区域冻结分佣
            $agency = UserRegion::get(['address' => $order->receiving_area]);

            if ($agency) {
                $agency_amount = 0;

                if (isset($giveaway_array['agency_receiving_area']) && $giveaway_array['agency_receiving_area'] > 0) {
                    $agency_scale = $giveaway_array['agency_receiving_area'];
                    if (isset($agency_scale) && $agency_scale > 0) {
                        $agency_raol = $agency_scale / 100;

                        if ($agency_raol > 0) {
                            $agency_amount = bcmul($v->pay_fee, $agency_raol, 2);
                        }

                        if ($agency_amount > 0) {
                            FrozenLog::create([
                                'user_id' => $agency->user_id,
                                'money' => $agency_amount,
                                'order_id' => $order->id,
                                'order_goods_id' => $v->id,
                                'memo' => '代理收货区域冻结分佣',
                                'source_type' => 404,
                            ]);
                        }
                    }
                }
            }
            if ($user->pid > 0) {
                $direct_amount = 0;
                $info = Info::where(['first_cate' => $v->first_cate, 'two_cate' => $v->two_cate, 'user_id' => $user->pid])->order('group_id desc')->find();

                if ($info) {
                    if ($info->group_id == 2) {
                        if (isset($giveaway_array['licensor_thrust']) && $giveaway_array['licensor_thrust'] > 0) {
                            $licensor_thrust = $giveaway_array['licensor_thrust'] / 100;
                            if ($licensor_thrust > 0) {
                                $direct_amount = bcmul($v->pay_fee, $licensor_thrust, 2);
                            }
                        }
                    }

                    if ($info->group_id == 3) {
                        if (isset($giveaway_array['partner_thrust']) && $giveaway_array['partner_thrust'] > 0) {
                            $partner_thrust = $giveaway_array['partner_thrust'] / 100;
                            if ($partner_thrust > 0) {
                                $direct_amount = bcmul($v->pay_fee, $partner_thrust, 2);
                            }
                        }
                    }
                } else {
                    if (isset($giveaway_array['dealer_thrust']) && $giveaway_array['dealer_thrust'] > 0) {
                        $dealer_thrust = $giveaway_array['dealer_thrust'] / 100;
                        if ($dealer_thrust > 0) {
                            $direct_amount = bcmul($v->pay_fee, $dealer_thrust, 2);
                        }
                    }
                }
                if ($direct_amount > 0) {
                    FrozenLog::create([
                        'user_id' => $user->pid,
                        'money' => $direct_amount,
                        'order_id' => $order->id,
                        'order_goods_id' => $v->id,
                        'memo' => '直推冻结佣金',
                        'source_type' => 400,
                    ]);
                }
            }
            $count = Region::where('category_id', $v->two_cate)->count();
            if ($count) {
                if ($user->paren_ids) {
                    $users = User::whereIn('id', $user->paren_ids)->order('id desc')->select();
                    $userinfo = Info::where(['first_cate' => $v->first_cate, 'two_cate' => $v->two_cate, 'user_id' => $user->id])->order('group_id desc')->find();
                    if ($userinfo) {
                        $identity = $userinfo->group_id;
                    } else {
                        $identity = 0;
                    }
                    $level_ratio = true;
                    foreach ($users as $kk => $vv) {
                        $level_amount =  $range_amount = 0;
                        $infos = Info::where(['first_cate' => $v->first_cate, 'two_cate' => $v->two_cate, 'user_id' => $vv->id])->order('group_id desc')->find();
                        if ($infos) {
                            if ($vv->id != $user->pid) {
                                //平级冻结金额
                                if ($identity == $infos->group_id && $level_ratio == true) {
                                    if ($infos->group_id == 2) {
                                        if (isset($giveaway_array['licensor_grade']) && $giveaway_array['licensor_grade'] > 0) {
                                            $licensor_grade = $giveaway_array['licensor_grade'] / 100;
                                            if ($licensor_grade > 0) {
                                                $level_amount = bcmul($v->pay_fee, $licensor_grade, 2);
                                            }
                                        }
                                    }
                                    if ($infos->group_id == 3) {
                                        if (isset($giveaway_array['partner_grade']) && $giveaway_array['partner_grade'] > 0) {
                                            $partner_grade = $giveaway_array['partner_grade'] / 100;
                                            if ($partner_grade > 0) {
                                                $level_amount = bcmul($v->pay_fee, $partner_grade, 2);
                                            }
                                        }
                                    }
                                    if ($level_amount > 0) {
                                        $level_ratio = false;
                                        FrozenLog::create([
                                            'user_id' => $vv->id,
                                            'money' => $level_amount,
                                            'order_id' => $order->id,
                                            'order_goods_id' => $v->id,
                                            'memo' => '平级冻结佣金',
                                            'source_type' => 401,
                                        ]);
                                    }
                                }
                            }
                            if ($range_ratio <= 0) {
                                continue;
                            }
                            //极差冻结金额
                            if ($user->group_id == 1) {
                                if ($infos->group_id == 2 && $infos->group_id > $identity) {
                                    if (isset($giveaway_array['licensor_difference']) && $giveaway_array['licensor_difference'] > 0) {
                                        $licensor_difference = $giveaway_array['licensor_difference'] / 100;
                                        if ($licensor_difference > 0) {
                                            $range_amount = bcmul($v->pay_fee, $licensor_difference, 2);
                                        }
                                        $range_ratio -= $giveaway_array['licensor_difference'];
                                    }
                                }
                                if ($infos->group_id == 3 && $infos->group_id > $identity) {
                                    if (isset($range_ratio) && $range_ratio > 0) {
                                        $partner_difference = $range_ratio / 100;
                                        if ($partner_difference > 0) {
                                            $range_amount = bcmul($v->pay_fee, $partner_difference, 2);
                                        }
                                        $range_ratio = 0;
                                    }
                                }
                            } else {
                                $my_group = Info::where(['first_cate' => $v->first_cate, 'two_cate' => $v->two_cate, 'user_id' => $user->id])->order('group_id desc')->find();

                                if (!$my_group) {

                                    if ($infos->group_id == 2 && $infos->group_id > $identity) {
                                        if (isset($giveaway_array['licensor_difference']) && $giveaway_array['licensor_difference'] > 0) {
                                            $licensor_difference = $giveaway_array['licensor_difference'] / 100;
                                            if ($licensor_difference > 0) {
                                                $range_amount = bcmul($v->pay_fee, $licensor_difference, 2);
                                            }
                                            $range_ratio -= $giveaway_array['licensor_difference'];
                                        }
                                    }

                                    if ($infos->group_id == 3 && $infos->group_id > $identity) {
                                        if (isset($range_ratio) && $range_ratio > 0) {
                                            $partner_difference = $range_ratio / 100;
                                            if ($partner_difference > 0) {
                                                $range_amount = bcmul($v->pay_fee, $partner_difference, 2);
                                            }
                                            $range_ratio = 0;
                                        }
                                    }
                                } else {

                                    if ($my_group->group_id == 2 && $infos->group_id == 3) {
                                        $range_ratio = bcsub($range_ratio, $giveaway_array['licensor_difference'], 2);
                                        if (isset($range_ratio) && $range_ratio > 0) {
                                            $partner_difference = $range_ratio / 100;
                                            if ($partner_difference > 0) {
                                                $range_amount = bcmul($v->pay_fee, $partner_difference, 2);
                                            }
                                            $range_ratio = 0;
                                        }
                                    }
                                }
                            }
                            if ($range_amount > 0) {
                                FrozenLog::create([
                                    'user_id' => $vv->id,
                                    'money' => $range_amount,
                                    'order_id' => $order->id,
                                    'order_goods_id' => $v->id,
                                    'memo' => '极差冻结佣金',
                                    'source_type' => 402,
                                ]);
                            }
                            if ($infos->group_id > $identity) {
                                $identity = $infos->group_id;
                            }
                        }
                    }
                }
            }
        }
        return true;
    }
    /**
     * @author LK
     * @date: 2023-10-23 
     * @param array $order  订单分佣
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static function commission($orders)
    {
        Db::startTrans();
        try {
            $settlement_day = config('site.settlement_time');
            $settlement_time = $settlement_day * 24 * 60 * 60;
            $time = time();
            foreach ($orders as $order) {
                if ($order->taketime + $settlement_time > $time) {
                    continue;
                }
                $goods = Goods::all(['order_id' => $order['id']]);
                foreach ($goods as $v) {
                    if ($v->is_settle == 1) {
                        continue;
                    }
                    $giveaway_array = json_decode($v->giveaway_info, true);
                    if (!$giveaway_array) {
                        $v->is_settle = 1;
                        $v->save();
                        continue;
                    }

                    $frozen  = FrozenLog::all(['order_id' => $order->id,  'order_goods_id' => $v->id]);
                    if ($frozen) {
                        foreach ($frozen as  $vo) {
                            //直推金额
                            if ($vo['source_type'] == 400) {
                                MoneyLog::income($vo->user_id, $vo->money, 1, 200, $order->sn, $v->id, $order->user_id);
                            } else if ($vo['source_type'] == 401) {
                                MoneyLog::income($vo->user_id, $vo->money, 1, 201, $order->sn, $v->id, $order->user_id);
                            } else if ($vo['source_type'] == 402) {
                                MoneyLog::income($vo->user_id, $vo->money, 1, 202, $order->sn, $v->id, $order->user_id);
                            } else if ($vo['source_type'] == 403) {
                                MoneyLog::income($vo->user_id, $vo->money, 1, 203, $order->sn, $v->id, $order->user_id);
                            } else if ($vo['source_type'] == 404) {
                                MoneyLog::income($vo->user_id, $vo->money, 1, 204, $order->sn, $v->id, $order->user_id);
                            }
                            $vo->delete();
                        }
                    }

                    $v->is_settle = 1;
                    $v->save();
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e);
        }
        return true;
    }
}
